﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using ReportWizard.Controls;
using ReportWizard.DataAccess;
using ReportWizard.Entities;
using ReportWizard.Helpers;
using ReportWizard.Properties;

namespace ReportWizard.Forms
{
    public partial class SelectImagesForm : IconForm
    {
        public int CurrentBookmarkId { get; set; }

        public string ImageFolderPath { get; set; }

        public string[] ImageFiles { get; set; }

        private ReportImageFileList CurrentPhotoSet { get; set; }

        public SelectImagesForm(int currentBookmarkId)
        {
            InitializeComponent();
            SetupForm();

            CurrentBookmarkId = currentBookmarkId;
        }

        public SelectImagesForm(int currentBookmarkId, string imageFolderPath)
        {
            InitializeComponent();
            SetupForm();

            CurrentBookmarkId = currentBookmarkId;
            ImageFolderPath = imageFolderPath;
        }

        public SelectImagesForm(int currentBookmarkId, string[] imageFiles)
        {
            InitializeComponent();
            SetupForm();

            CurrentBookmarkId = currentBookmarkId;
            ImageFiles = imageFiles;
        }

        private void SetupForm()
        {
            //ShowCustomLeftButton = false;
            ShowCustomRightButton = false;
            ShowCancelButton = false;
            ShowCheckFooter = false;
        }

        private bool IsValidImage(string fileName)
        {
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    return IsValidImage(fs);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                if (ex is IOException)
                    throw;
                return false;
            }
        }
        
        private bool IsValidImage(Stream stream)
        {
            try
            {
                stream.Position = 0;
                stream.Seek(0, SeekOrigin.Begin);
                
                using (Image img = Image.FromStream(stream))
                {
                    img.Dispose();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return false;
            }
        }

        private void GetMatchedFiles(string[] fileNames)
        {
            try
            {
                List<ReportImageFile> matchedFiles = new List<ReportImageFile>();

                if (Globals.CurrentReport.PhotoCollection != null)
                {
                    CurrentPhotoSet =
                        Globals.CurrentReport.PhotoCollection.Where(i => i.BookmarkId == CurrentBookmarkId).
                            FirstOrDefault();
                }

                for (int i = 0; i < fileNames.Length; i++)
                {
                    bool addingGranted = true;
                    FileInfo fi = new FileInfo(fileNames[i]);
                    if (fi.Exists && fi.Length > 0)
                    {
                        if (CurrentPhotoSet != null)
                        {
                            if (
                                CurrentPhotoSet.Photos.Where(photo => photo.FilePath.Equals(fi.FullName)).
                                    FirstOrDefault() != null)
                            {
                                addingGranted = false;
                            }
                        }

                        if (IsValidImage(fi.FullName) && addingGranted)
                        {
                            ReportImageFile rif = new ReportImageFile
                                                        {
                                                            FileName = fi.Name,
                                                            FilePath = fi.FullName,
                                                            Checked = true
                                                        };

                            matchedFiles.Add(rif);
                        }
                    }
                }
                matchedFiles.Sort(new ReportImageFile());

                if (Globals.CurrentReport.PhotoCollection != null)
                {
                    if (CurrentPhotoSet != null)
                    {
                        CurrentPhotoSet.Photos.AddRange(matchedFiles);
                    }
                    else
                    {
                        ReportImageFileList newPhotoSet = new ReportImageFileList(CurrentBookmarkId)
                                                              {
                                                                  Photos = new List<ReportImageFile>()
                                                              };

                        newPhotoSet.Photos.AddRange(matchedFiles);

                        Globals.CurrentReport.PhotoCollection.Add(newPhotoSet);

                        CurrentPhotoSet = newPhotoSet;
                    }
                }
                else
                {
                    Globals.CurrentReport.PhotoCollection = new List<ReportImageFileList>();

                    ReportImageFileList newPhotoSet = new ReportImageFileList(CurrentBookmarkId)
                                                          {
                                                              Photos = new List<ReportImageFile>()
                                                          };

                    newPhotoSet.Photos.AddRange(matchedFiles);

                    Globals.CurrentReport.PhotoCollection.Add(newPhotoSet);

                    CurrentPhotoSet = newPhotoSet;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }

        private void FillFileListView()
        {
            if (pPhotoList.Controls.Count != 0)
            {
                pPhotoList.Controls.Clear();
            }

            CustomLeftButtonText = Perferences.ViewPhotoListAsThumbnails ? Resources.List : Resources.Thumbnails;

            if (Perferences.ViewPhotoListAsThumbnails)
            {
                PhotoListThumbnails photoList = new PhotoListThumbnails(CurrentPhotoSet);
                pPhotoList.Controls.Add(photoList);
            }
            else
            {
                PhotoListDetails photoList = new PhotoListDetails(CurrentPhotoSet);
                pPhotoList.Controls.Add(photoList);
            }

            if (!Created)
            {
                ShowDialog();
            }
        }

        public void FillFileListFromFolder()
        {
            pPhotoList.Controls.Clear();

            string[] fileList = Directory.GetFiles(ImageFolderPath, "*.jpg");
            if (fileList.Length != 0)
            {
                GetMatchedFiles(fileList);

                if (CurrentPhotoSet != null && CurrentPhotoSet.Photos.Count != 0)
                {
                    FillFileListView();
                }
                else
                {
                    ImageFolderPath = string.Empty;
                    ShowMessage.Info(Resources.PhotosNotFound);
                }
            }
            else
            {
                ImageFolderPath = string.Empty;
                ShowMessage.Info(Resources.PhotosNotFound);
            }
        }

        public void FillFileListFromFileNames()
        {
            pPhotoList.Controls.Clear();
            
            if (ImageFiles.Length != 0)
            {
                GetMatchedFiles(ImageFiles);

                if (CurrentPhotoSet != null && CurrentPhotoSet.Photos.Count != 0)
                {
                    FillFileListView();
                }
                else
                {
                    ImageFolderPath = string.Empty;
                }
            }
            else
            {
                ImageFolderPath = string.Empty;
            }
        }

        public void FillFileListFromGlobal()
        {
            pPhotoList.Controls.Clear();

            if (Globals.CurrentReport != null && Globals.CurrentReport.PhotoCollection != null)
            {
                CurrentPhotoSet = Globals.CurrentReport.PhotoCollection.Where(i => i.BookmarkId == CurrentBookmarkId).FirstOrDefault();
                if (CurrentPhotoSet != null && CurrentPhotoSet.Photos.Count != 0)
                {
                    FillFileListView();
                }
            }
        }

        private void SelectImagesForm_ClickOk(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void SelectImagesForm_Load(object sender, EventArgs e)
        {
            HeaderText = string.Format("Список фото и изображений для закладки \"{0}\"", Globals.TargetFormProfile.Replace('_',' '));
        }

        private void SelectImagesForm_ClickCustomLeft(object sender, EventArgs e)
        {
            Perferences.ViewPhotoListAsThumbnails = !Perferences.ViewPhotoListAsThumbnails;
            FillFileListView();
        }
    }
}
